﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace GA.Shared.Interfaces
{
    [Serializable]
    public class SerializableTransferObject
    {
        public Dictionary<string, object> Properties
        {
            get { return mProperties; }
            private set { mProperties = value; }
        }

        public string OutputType
        {
            get { return mOutputType; }
            private set { mOutputType = value; }
        }

        public SerializableTransferObject()
        {
        }

        public SerializableTransferObject(LinkedDependencyObject baseObject)
        {
            Properties = new Dictionary<string, object>();
            Type linkedDependencyObjectType = baseObject.GetType();
            foreach (PropertyInfo propertyInfo in linkedDependencyObjectType.GetProperties())
            {
                if (propertyInfo.CanRead 
                    && propertyInfo.CanWrite 
                    && !propertyInfo.PropertyType.IsAssignableFrom(typeof(LinkedDependencyObject))
                    && !propertyInfo.PropertyType.IsAssignableFrom(typeof(IEnumerable<LinkedDependencyObject>)))
                {
                    Properties.Add(propertyInfo.Name, propertyInfo.GetValue(baseObject, null));
                }
            }
            mOutputType = linkedDependencyObjectType.Name;
        }

        public T ConvertToLinkedDependencyObject<T>() where T : LinkedDependencyObject
        {
            Type linkedDependencyObjectType = typeof(T);
            return (T)linkedDependencyObjectType.GetConstructor(new Type[] { typeof(SerializableTransferObject) }).Invoke(new object[] { this });
        }

        private Dictionary<string, object> mProperties;
        private string mOutputType;
    }
}
